package valuecomusa.fijibus.eticket.shorthaul;


import android.app.AlertDialog;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.media.MediaPlayer;
//import android.nfc.NfcAdapter;
import android.os.*;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.*;
import valuecomusa.fijibus.eticket.*;
import valuecomusa.fijibus.eticket.db.shorthaul.BusinessDBHandler;
import valuecomusa.fijibus.eticket.db.shorthaul.GpsDBHandler;
import valuecomusa.fijibus.eticket.dialog.refund;
import valuecomusa.fijibus.eticket.dto.GpsCurrentLocationValue;
import valuecomusa.fijibus.eticket.dto.StagesOfRouteValue;
import valuecomusa.fijibus.eticket.ws.MemberValue;
import valuecomusa.fijibus.eticket.ws.PassengerTypeValue;
import valuecomusa.fijibus.eticket.ws.TransactionValue;
import valuecomusa.fijibus.eticket.ws.VoucherValue;

import java.util.Date;
import java.util.List;

public class CheckInV2CashMultiple extends SunbeamActivity
{
	private static int counter = 1;
    private String TAG = "CheckInV2CashMultiple";
	//--
    private StagesOfRouteValue currentLocation;
    private RadioGroup adult;
    private RadioGroup senior;
    private RadioGroup child;
    private RadioGroup disabled;
    //private RadioGroup exempt;
    private RadioGroup student;

    private int passengerCount = 0;
    private double totalAmount;
    private double xStageFare;
    private int stageCount;
    //--
    //private double minFare;

    private TextView totalAmountTextView;
    /*private CheckBox printReceipt;*/

    private BusinessDBHandler db;
    private GpsDBHandler gpsDb;

//    private NfcAdapter nfcAdapter;
//    private PendingIntent mPendingIntent;

    private List<PassengerTypeValue> passengerTypeList;
    //--
    private ProgressDialog progress;
	//--
	private boolean processing = false;

	public CheckInV2CashMultiple()
	{
		TAG = TAG + "." + counter++;
		if(counter > 1000000)
			counter = 1;
	}

    public int getSelectedPassenger(RadioGroup g)
    {
        if (g == null)
            return 0;

        int selected = g.getCheckedRadioButtonId();
        if (selected < 0)
            return 0;

        RadioButton b = (RadioButton) findViewById(selected);

        return Integer.parseInt(b.getText().toString());
    }

    private double GetPassengerTypeDiscount(String type)
    {
        for (PassengerTypeValue xx : this.passengerTypeList)
        {
            if (xx.Type.toLowerCase().equals(type.toLowerCase()))
                return xx.Discount / 100;
        }
        return 0;
    }

    public void CalcTotalAmount()
    {
        int tmpNoOf = 0;
        try
        {
            totalAmount = 0;
            passengerCount = 0;
            double discount = 0;
            //--
            tmpNoOf = getSelectedPassenger(adult);
            totalAmount = tmpNoOf * xStageFare * (1 - GetPassengerTypeDiscount("adult"));
            passengerCount = tmpNoOf;
            //--
            tmpNoOf = getSelectedPassenger(senior);
            totalAmount += tmpNoOf * xStageFare * (1 - GetPassengerTypeDiscount("senior"));
            passengerCount += tmpNoOf;
            //--
            tmpNoOf = getSelectedPassenger(child);
            totalAmount += tmpNoOf * xStageFare * (1 - GetPassengerTypeDiscount("child"));
            passengerCount += tmpNoOf;
            //--
            tmpNoOf = getSelectedPassenger(disabled);
            totalAmount += tmpNoOf * xStageFare * (1 - GetPassengerTypeDiscount("disabled"));
            passengerCount += tmpNoOf;
            //--
            /*tmpNoOf = getSelectedPassenger(exempt);
            totalAmount += tmpNoOf * xStageFare * (1 - GetPassengerTypeDiscount("exempt"));
            passengerCount += tmpNoOf;*/
            //--
            tmpNoOf = getSelectedPassenger(student);
            totalAmount += tmpNoOf * xStageFare * (1 - GetPassengerTypeDiscount("student"));
            passengerCount += tmpNoOf;
            //--
            totalAmountTextView.setText(String.valueOf(WorkingSession.getInstance().RoundMoney(totalAmount)));
        }
        catch (Exception ex)
        {
            Log.e(TAG, ex.getMessage());
        }
    }

    private void Initialize()
    {
//		nfcAdapter = NfcAdapter.getDefaultAdapter(this);
//        mPendingIntent = PendingIntent.getActivity(this, 0, new Intent(this,
//                getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
		//--
        currentLocation = null;
        passengerCount = 0;
        totalAmount = 0;
        xStageFare = 0;
        stageCount = 1;
		//--
		passengerTypeList = db.getPassengerType();
		if (passengerTypeList == null || passengerTypeList.size() == 0)
		{
			Log.d(TAG, "Could not get Passenger Type discount");
			WorkingSession.getInstance().ShowToast(this,
					"Could not get Passenger Type's discount",
					Toast.LENGTH_LONG);
			finish();
			return;
		}
        //--
        totalAmountTextView = (TextView) findViewById(R.id.check_in_multiple_total_fare_text);
        //printReceipt = (CheckBox) findViewById(R.id.chkPrintReceipt);
        //---
        adult = (RadioGroup) findViewById(R.id.Adult);
        senior = (RadioGroup) findViewById(R.id.Senior);
        child = (RadioGroup) findViewById(R.id.Child);
        disabled = (RadioGroup) findViewById(R.id.Disabled);
        //exempt = (RadioGroup) findViewById(R.id.Exempt);
        student = (RadioGroup) findViewById(R.id.Student);
		//--
		findViewById(R.id.checkin_btn_tap_out).setEnabled(false);
		//--
		RadioGroup stageGroup1 = (RadioGroup) findViewById(R.id.stageGroup1);
		stageGroup1.check(R.id.checkin_btStage1);
		//--
		RegisterCheckedChangeEvent();
		RegisterPayByButtonEvent();
		//--
		GetFare(R.id.checkin_btStage1);
		adult.check(R.id.Adult1);
		//---
		fillMemberInfo();
    }

    /*private int getCheckInType()
    {
        Intent input = getIntent();
        int x = input.getIntExtra("CHECK-IN_TYPE", Declarations.CHECK_IN_TYPE_NO_CARD);
        return x;
    }*/

    private void fillMemberInfo()
    {
        TextView tvtmp = (TextView) findViewById(R.id.tvCustID);
        tvtmp.setText(WorkingSession.getInstance().currentPassenger.UserName + " ("
                + WorkingSession.getInstance().currentPassenger.getFullName() + ")");
    }

    private void showStageButton()
    {
        RadioGroup stageGroup1 = (RadioGroup) findViewById(R.id.stageGroup1);
        RadioGroup stageGroup2 = (RadioGroup) findViewById(R.id.stageGroup2);

        int xCount = db.getStageCountOfRoute(WorkingSession.getInstance().journalRoute.ISN);
        if (xCount <= 0)
        {
            stageGroup1.setVisibility(View.GONE);
            stageGroup2.setVisibility(View.GONE);
            return;
        }
        if (xCount < 4)
        {
            stageGroup2.setVisibility(View.GONE);
            if (xCount < 3)
                findViewById(R.id.checkin_btStage3).setVisibility(View.GONE);
            if (xCount < 2)
                findViewById(R.id.checkin_btStage2).setVisibility(View.GONE);
        } else
        {
            if (xCount < 7)
                findViewById(R.id.checkin_btStage7).setVisibility(View.GONE);
            if (xCount < 6)
                findViewById(R.id.checkin_btStage6).setVisibility(View.GONE);
            if (xCount < 5)
                findViewById(R.id.checkin_btStage5).setVisibility(View.GONE);
        }
    }

    /*private void showPayByButtons(int type)
    {
        *//*checkin_layout_payby_no_tap_1
        checkin_layout_payby_no_tap_2
        checkin_layout_payby_nocard
        checkin_layout_tap_in_out*//*
        if (type == checkinType)
            return;

        checkinType = type;

        if (checkinType == Declarations.CHECK_IN_TYPE_NO_CARD)
        {
            TextView title = (TextView) findViewById(R.id.title_text);
            title.setText(getString(R.string.title_activity_check_in_no_card));

            //--
            LinearLayout layout = (LinearLayout) findViewById(R.id.checkin_layout_tap_in_out);
            layout.setVisibility(View.GONE);
            //--
            layout = (LinearLayout) findViewById(R.id.checkin_layout_payby_no_tap_1);
            layout.setVisibility(View.VISIBLE);
            layout = (LinearLayout) findViewById(R.id.checkin_layout_payby_no_tap_2);
            layout.setVisibility(View.VISIBLE);
            //--
            //--Current balance and total fare group
            //--
            layout = (LinearLayout) findViewById(R.id.checkin_layout_total_fare);
            layout.setVisibility(View.VISIBLE);
            //--
            layout = (LinearLayout) findViewById(R.id.checkin_layout_current_balance_small);
            layout.setVisibility(View.GONE);
            //--
            layout = (LinearLayout) findViewById(R.id.checkin_layout_current_balance);
            layout.setVisibility(View.GONE);
            //--
            layout = (LinearLayout) findViewById(R.id.checkin_layout_print_receipt);
            layout.setVisibility(View.VISIBLE);
            //--Pay by buttons
            Button button = (Button) findViewById(R.id.btByAcct);
            button.setEnabled(false);
            //-
            button = (Button) findViewById(R.id.btByCash);
            button.setEnabled(true);
            //-
            button = (Button) findViewById(R.id.checkin2_btn_cash_topup);
            button.setEnabled(false);
            //-
            button = (Button) findViewById(R.id.check_in2_payby_student_voucher);
            button.setEnabled(false);
            //-
            button = (Button) findViewById(R.id.checkin_m_paisa);
            button.setEnabled(false);
        }
        else if (checkinType == Declarations.CHECK_IN_TYPE_NORMAL)
        {
            TextView title = (TextView) findViewById(R.id.title_text);
            title.setText(getString(R.string.title_activity_check_in));
            //--
            LinearLayout layout = (LinearLayout) findViewById(R.id.checkin_layout_tap_in_out);
            layout.setVisibility(View.GONE);
            //--
            layout = (LinearLayout) findViewById(R.id.checkin_layout_payby_no_tap_1);
            layout.setVisibility(View.VISIBLE);
            layout = (LinearLayout) findViewById(R.id.checkin_layout_payby_no_tap_2);
            layout.setVisibility(View.VISIBLE);
            //--
            //--Current balance and total fare group
            //--
            layout = (LinearLayout) findViewById(R.id.checkin_layout_total_fare);
            layout.setVisibility(View.VISIBLE);
            //--
            layout = (LinearLayout) findViewById(R.id.checkin_layout_current_balance_small);
            layout.setVisibility(View.VISIBLE);
            //--
            layout = (LinearLayout) findViewById(R.id.checkin_layout_current_balance);
            layout.setVisibility(View.GONE);
            //--
            layout = (LinearLayout) findViewById(R.id.checkin_layout_print_receipt);
            layout.setVisibility(View.VISIBLE);
            //--Pay by buttons
            Button button = (Button) findViewById(R.id.btByAcct);
            button.setEnabled(true);
            //-
            button = (Button) findViewById(R.id.btByCash);
            button.setEnabled(true);
            //-
            button = (Button) findViewById(R.id.checkin2_btn_cash_topup);
            button.setEnabled(true);
            //-
            button = (Button) findViewById(R.id.check_in2_payby_student_voucher);
            button.setEnabled(false);
            //-
            button = (Button) findViewById(R.id.checkin_m_paisa);
            button.setEnabled(false);
        } else if (checkinType == Declarations.CHECK_IN_TYPE_TAP_IN)
        {
            TextView title = (TextView) findViewById(R.id.title_text);
            title.setText(getString(R.string.title_activity_check_in));
            //--
            LinearLayout layout = (LinearLayout) findViewById(R.id.checkin_layout_payby_no_tap_1);
            layout.setVisibility(View.GONE);
            layout = (LinearLayout) findViewById(R.id.checkin_layout_payby_no_tap_2);
            layout.setVisibility(View.GONE);
            //--
            layout = (LinearLayout) findViewById(R.id.checkin_layout_tap_in_out);
            layout.setVisibility(View.VISIBLE);

            //--
            //--Current balance and total fare group
            //--
            layout = (LinearLayout) findViewById(R.id.checkin_layout_total_fare);
            layout.setVisibility(View.GONE);
            //--
            layout = (LinearLayout) findViewById(R.id.checkin_layout_current_balance_small);
            layout.setVisibility(View.GONE);
            //--
            layout = (LinearLayout) findViewById(R.id.checkin_layout_current_balance);
            layout.setVisibility(View.VISIBLE);
            //--
            layout = (LinearLayout) findViewById(R.id.checkin_layout_print_receipt);
            layout.setVisibility(View.GONE);
        }
    }*/

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        Log.d(TAG, "onCreate...");
        // --
        setContentView(R.layout.check_in_v2_cash_multiple);
        WorkingSession.getInstance().currentActivity = CheckInV2CashMultiple.this;
        // --
        doCommon();
		//--
		db = new BusinessDBHandler(CheckInV2CashMultiple.this);
		gpsDb = new GpsDBHandler(CheckInV2CashMultiple.this);
		//--
        Initialize();
		ChangeTitle();
		//--
        progress = new ProgressDialog(this);
        progress.setMessage("Waiting...");
        progress.setCancelable(false);
        //--
        HandlerThread uiThread = new HandlerThread("UIThreadHandler");//to prepare a looper
        uiThread.start();
        uiThreadHandler = new UIThreadHandler(uiThread.getLooper()); //to process UI such as AlertDialog,...
        //--

        //minFare = db.getStageFare(WorkingSession.getInstance().journalRoute.ISN, 1);

        //--
        List<StagesOfRouteValue> stageList = db.getStagesOfRoute(WorkingSession.getInstance().journalRoute.ISN);
        ArrayAdapter<StagesOfRouteValue> stages = new ArrayAdapter<StagesOfRouteValue>(this,
                android.R.layout.simple_dropdown_item_1line, stageList);
        //---
        Spinner xx = (Spinner) findViewById(R.id.checkin_current_location);
        xx.setAdapter(stages);
        xx.setOnItemSelectedListener(currentLocationItemClick);
        //---
        Button xxClick = (Button) findViewById(R.id.checkin_current_location_click);
        xxClick.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View view)
            {
                Spinner xx = (Spinner) findViewById(R.id.checkin_current_location);
                xx.performClick();
            }
        });
        //--

        //--
        //RegisterPassengerTypeTouchEvent();
        //--
        showStageButton();
        //RegisterStageTouchEvent();
        //----


        //---
        if (xStageFare < 0)
        {
            WorkingSession.getInstance().ShowToast(this, "Could not get Fare", Toast.LENGTH_LONG);
        }
        //--
        GpsCurrentLocationValue currentGpsLocation = gpsDb.getCurrentLocation(
                WorkingSession.getInstance().setupJournal.ISN);
        if (currentGpsLocation != null)
        {
            Log.d(TAG, String.format("Current location: %d", currentGpsLocation.ClosestStage));
            int idx = -1;
            for (int i = 0; i < stageList.size(); i++)
            {
                Log.d(TAG, String.format("Stage: %d", stageList.get(i).StageISN));
                if (stageList.get(i).StageISN == currentGpsLocation.ClosestStage &&
                        stageList.get(i).BusStationISN == currentGpsLocation.ClosestBusStation)
                {
                    idx = i;
                    break;
                }
            }
            if (idx != -1)
                xx.setSelection(idx);
        }
        //-- play bula voice
        //Utilities.PlayMedia(CheckIn.this, "bula.mp3");
        //---
        //CheckBalanceAndAutoSubmit();
    }

    private AdapterView.OnItemSelectedListener currentLocationItemClick = new AdapterView.OnItemSelectedListener()
    {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long rowId)
        {
            StagesOfRouteValue sel = (StagesOfRouteValue) parent.getItemAtPosition(position);

            Log.d(TAG, String.format("Select location: %d - %s", sel.StageISN, sel.StationName));
            currentLocation = sel;
        }

        @Override
        public void onNothingSelected(AdapterView<?> adapterView)
        {
            currentLocation = null;
        }
    };

    private void RegisterCheckedChangeEvent()
    {
        //--
        adult.setOnCheckedChangeListener(onPassengerCheckedChange);
        senior.setOnCheckedChangeListener(onPassengerCheckedChange);
        child.setOnCheckedChangeListener(onPassengerCheckedChange);
        disabled.setOnCheckedChangeListener(onPassengerCheckedChange);
        //exempt.setOnCheckedChangeListener(onPassengerCheckedChange);
        student.setOnCheckedChangeListener(onPassengerCheckedChange);
        //---
        RadioGroup stageSelect;
        //---stage group 1
        stageSelect = (RadioGroup) findViewById(R.id.stageGroup1);
        stageSelect.setOnCheckedChangeListener(onStageCheckedChange);
        //---stage group 2
        stageSelect = (RadioGroup) findViewById(R.id.stageGroup2);
        stageSelect.setOnCheckedChangeListener(onStageCheckedChange);
        //---
        /*Button bycash = (Button) findViewById(R.id.btByCash);
        bycash.setOnClickListener(onPaybyCash);
        bycash.setOnTouchListener(onTouch);*/
        //--
        /*Button payAccount = (Button) findViewById(R.id.btByAcct);
        payAccount.setOnClickListener(onPaybyBMF);
        payAccount.setOnTouchListener(onTouch);*/
        //--
        /*Button payStudent = (Button) findViewById(R.id.check_in2_payby_student_voucher);
        payStudent.setOnClickListener(onStudentVoucherClick);
        payStudent.setOnTouchListener(onTouch);*/
        //--
        /*Button cash_topup = (Button) findViewById(R.id.checkin2_btn_cash_topup);
        cash_topup.setOnClickListener(onCashAndTopUpClick);
        cash_topup.setOnTouchListener(onTouch);*/
        //--
        /*Button cancel = (Button) findViewById(R.id.check_in_tap_cancel);
        cancel.setOnClickListener(onCancelClick);
        cancel.setOnTouchListener(onTouch);*/
        //--
        /*Button submit = (Button) findViewById(R.id.check_in_tap_submit);
        submit.setOnClickListener(onSubmitClick);
        submit.setOnTouchListener(onTouch);*/
        //--
        /*Button tap_cash_topup = (Button) findViewById(R.id.checkin_tap_cash_topup);
        tap_cash_topup.setOnClickListener(onCashAndTopUpClick);
        tap_cash_topup.setOnTouchListener(onTouch);*/
    }

    private MediaPlayer errorVoice;
    /*private void CheckBalanceAndAutoSubmit()
    {
        if (WorkingSession.getInstance().currentPassenger.CurrentBalance < minFare
                && checkinType == Declarations.CHECK_IN_TYPE_TAP_IN)
        {
            Intent runActivity = new Intent(CheckInV2CashMultiple.this, checkin_topup.class);
            runActivity.putExtra("REQUIRED_FARE_AMOUNT", minFare);
            startActivityForResult(runActivity, Declarations.REQUEST_REQUIRED_TOP_UP);
            return;
        }
        if (checkinType == Declarations.CHECK_IN_TYPE_TAP_IN)
        {
            autoSubmit = new Timer();
            autoSubmit.scheduleAtFixedRate(
                    autoSubmitTask,
                    0,
                    1000);
        }
        else if (checkinType == Declarations.CHECK_IN_TYPE_NORMAL
                && WorkingSession.getInstance().currentPassenger.CurrentBalance < 0)
        {
            errorVoice = Utilities.PlayMedia(CheckInV2CashMultiple.this, "insufficient-balance.mp3");
            //--
            TextView balanceText = (TextView) findViewById(R.id.checkin_current_balance);
            balanceText.setTextColor(Color.RED);
            //--
            Button byCash = (Button) findViewById(R.id.btByCash);
            byCash.setEnabled(false);
            //--
            Button payAccount = (Button) findViewById(R.id.btByAcct);
            payAccount.setEnabled(false);
        }
    }*/

    private UIThreadHandler uiThreadHandler;

    @Override
    protected void onStart()
    {
        super.onStart();
        Log.d(TAG, "onStart...");
        //Toast.makeText(CheckInV2CashMultiple.this, "Start", Toast.LENGTH_SHORT).show();

    }

    /*private TimerTask autoSubmitTask = new TimerTask()
    {
        @Override
        public void run()
        {
            uiThreadHandler.sendEmptyMessage(UIThreadHandler.MSG_COUNT_DOWN);
        }
    };*/

    /*@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK)
        {
            if (requestCode == Declarations.REQUEST_CASH_TOP_UP)
            {
                double cashTopUpAmount = data.getDoubleExtra("CASH_TOPUP_AMOUNT", 0);
                if (cashTopUpAmount > 0)
                {
                    //doPayCashAndTopUp(cashTopUpAmount);
                    DoCheckInAsync xTask = new DoCheckInAsync(
                            CheckInV2CashMultiple.this,
                            progress,
                            DoCheckInAsync.CHECK_IN_BY_CASH_TOP_UP
                    );
                    xTask.execute(cashTopUpAmount);
                }
            }
            else if (requestCode == Declarations.REQUEST_STUDENT_VOUCHER)
            {
                double discountAmount = data.getDoubleExtra("VOUCHER_DISCOUNT_AMOUNT", 0);
                String voucherType = data.getStringExtra("VOUCHER_TYPE");
                int collectBalanceType = data.getIntExtra("VOUCHER_COLLECT_BALANCE_TYPE",
                        StudentVoucher.COMPLETE_PAYMENT_BY_VOUCHER);
                double collectAmount = data.getDoubleExtra("VOUCHER_COLLECT_CASH", 0);
                //--
                *//*doPayByStudentVoucher(
                        voucherType,
                        discountAmount,
                        collectBalanceType,
                        collectAmount);*//*
                DoCheckInAsync xTask = new DoCheckInAsync(
                        CheckInV2CashMultiple.this,
                        progress,
                        DoCheckInAsync.CHECK_IN_BY_STUDENT_VOUCHER
                );
                xTask.execute(
                        voucherType,
                        discountAmount,
                        collectBalanceType,
                        collectAmount
                );
            }
            else if (requestCode == Declarations.REQUEST_REQUIRED_TOP_UP)
            {
                double topUpAmount = data.getDoubleExtra("TOP_UP_AMOUNT_RESULT", 0);
                if (topUpAmount > 0)
                {
                    if (AddTopUpTransaction(topUpAmount))
                    {
                        WorkingSession.getInstance().ShowToast(
                                CheckInV2CashMultiple.this,
                                "Add Top Up transaction successful",
                                Toast.LENGTH_SHORT
                        );

                        //doTapIn();
                        DoCheckInAsync xTask = new DoCheckInAsync(
                                CheckInV2CashMultiple.this,
                                progress,
                                DoCheckInAsync.CHECK_IN_BY_TAP_IN
                        );
                        xTask.execute();
                    }
                }
            }
        }
    }*/

    /*private boolean AddTopUpTransaction(double amount)
    {
        //--create top up transaction
        TransactionValue trans = WorkingSession.getInstance().CreateTransaction(
                CheckInV2CashMultiple.this,
                "TOP-UP",
                "Cash",
                0,
                0, 0,
                amount,
                null, //voucher
                null, null,
                0,
                0, 0, 0, 0, 0, 0,
                null,
                ";;;;;");
        if (trans == null)
        {
            WorkingSession.getInstance().ShowErrorDialog(
                    CheckInV2CashMultiple.this,
                    "Create Transaction Error",
                    "System Error.\nCould not create transaction, please contact your administrator."
            );

            return false;
        }
        try
        {
            long rx = db.addTransaction(trans);
            trans.ISN = (int) rx;
        }
        catch (Exception ex)
        {
            WorkingSession.getInstance().ShowErrorDialog(
                    CheckInV2CashMultiple.this,
                    "Create Transaction Error",
                    "System Error.\nCould not create transaction, please contact your administrator."
            );

            return false;
        }
        //--update passenger balance
        WorkingSession.getInstance().currentPassenger.CurrentBalance += trans.TopUpAmount;
        int x = db.updateMemberBalance(
                WorkingSession.getInstance().currentPassenger.ISN,
                WorkingSession.getInstance().currentPassenger.CurrentBalance);

        return true;
    }*/

    private int InputValidate()
    {
        int inputValidateResult = 1;

        if (currentLocation == null)
        {
            WorkingSession.getInstance().ShowErrorDialog(
                    CheckInV2CashMultiple.this,
                    "Error",
                    "Please select current location");

            inputValidateResult = 0;
        }
		else if (passengerCount <= 0)
        {
            WorkingSession.getInstance().ShowErrorDialog(
                    CheckInV2CashMultiple.this,
                    "Error",
                    "Please choose passenger type \n(Adult, Senior, Child, Disabled or Student)"
            );

            inputValidateResult = 0;
        }
		/*else if (paymentType == 0 &&//BMF
                checkinType != Declarations.CHECK_IN_TYPE_TAP_IN && //not tap-in
                WorkingSession.getInstance().currentPassenger.CurrentBalance < totalAmount)
        {
            WorkingSession.getInstance().ShowErrorDialog(
                    CheckInV2CashMultiple.this,
                    "Error",
                    "Customer is not enough balance for check-in"
            );

            inputValidateResult = 0;
        } else if (checkinType == Declarations.CHECK_IN_TYPE_TAP_IN)
        {
            if (WorkingSession.getInstance().currentPassenger.CurrentBalance < minFare)
            {
                WorkingSession.getInstance().ShowToast(
                        CheckInV2CashMultiple.this,
                        "Customer is not enough balance for check-in",
                        Toast.LENGTH_SHORT
                );

                inputValidateResult = 2;
            }
        }*/

        return inputValidateResult;
    }

    /*OnClickListener onPaybyBMF = new OnClickListener()
    {

        @Override
        public void onClick(View v)
        {
            //--
            if (InputValidate(0) != 1) //not validate or waiting for confirm
                return;

            //SetAllButtonState(false);
            //doPayByBMF();
            //SetAllButtonState(true);

            DoCheckInAsync xTask = new DoCheckInAsync(
                    CheckInV2CashMultiple.this,
                    progress,
                    DoCheckInAsync.CHECK_IN_BY_BMF
            );
            xTask.execute();
        }
    };*/

    OnClickListener onPaybyCash = new OnClickListener()
    {
        @Override
        public void onClick(View v)
        {

            //--
            if (InputValidate() != 1) //not validate or waiting for confirm
                return;

            /*SetAllButtonState(false);
            doPayByCash();
            SetAllButtonState(true);*/

            DoCheckInAsync xTask = new DoCheckInAsync(
                    CheckInV2CashMultiple.this,
                    progress,
                    DoCheckInAsync.CHECK_IN_BY_CASH
            );
            xTask.execute();
        }
    };

    /*OnClickListener onCashAndTopUpClick = new OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            //--
            if (InputValidate(2) < 0) //not validate or waiting for confirm
                return;

            Intent input = new Intent(CheckInV2CashMultiple.this, Cash_TopUp.class);
            input.putExtra("FARE_AMOUNT", totalAmount);
            startActivityForResult(input, Declarations.REQUEST_CASH_TOP_UP); //will be continued at onActivityResult
        }
    };*/

    OnClickListener onStudentVoucherClick = new OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            if (InputValidate() != 1) //not validate or waiting for confirm
                return;

			double discountAmount = (stageCount == 3? 0.75d : (stageCount == 2? 0.55d: 0.35d));
			String voucherType = (stageCount == 3? "Red" : (stageCount == 2? "Blue" : "Yellow"));
			int collectBalanceType = StudentVoucher.COMPLETE_PAYMENT_BY_VOUCHER;
			double collectAmount = 0;
			//--
			DoCheckInAsync xTask = new DoCheckInAsync(
					CheckInV2CashMultiple.this,
					progress,
					DoCheckInAsync.CHECK_IN_BY_STUDENT_VOUCHER
			);
			xTask.execute(
					voucherType,
					discountAmount,
					collectBalanceType,
					collectAmount
			);
        }
    };


    private int stageClearGroup;

    private RadioGroup.OnCheckedChangeListener onStageCheckedChange = new RadioGroup.OnCheckedChangeListener()
    {
        @Override
        public void onCheckedChanged(RadioGroup radioGroup, int i)
        {
            Log.d(TAG, "[onStageCheckedChange] id: " + i);

            if (radioGroup.getId() == stageClearGroup)
            {
                stageClearGroup = 0;
                return;
            }

            if (i == -1)
                return;

            GetFare(radioGroup.getCheckedRadioButtonId());
            CalcTotalAmount();
            //--
            if (radioGroup.getId() == R.id.stageGroup1)
            {
                stageClearGroup = R.id.stageGroup2;
                ((RadioGroup) findViewById(R.id.stageGroup2)).clearCheck();
            } else
            {
                stageClearGroup = R.id.stageGroup1;
                ((RadioGroup) findViewById(R.id.stageGroup1)).clearCheck();
            }
            if (xStageFare < 0)
            {
                WorkingSession.getInstance().ShowToast(CheckInV2CashMultiple.this, "Could not get Fare", Toast.LENGTH_SHORT);
            }

			/*if(getSelectedPassenger(student) > 0) //pay by student voucher
			{
				onStudentVoucherClick.onClick(null);
			}
			else
				uiThreadHandler.sendEmptyMessage(UIThreadHandler.DO_CHECK_IN_BY_CASH);*/
        }
    };

    private void GetFare(int stageButtonId)
    {
        if (stageButtonId == R.id.checkin_btn_tap_out)
        {
            int xCount = db.getStageCountOfRoute(WorkingSession.getInstance().journalRoute.ISN);
            xStageFare = db.getStageFare(WorkingSession.getInstance().journalRoute.ISN, xCount);
            stageCount = xCount;
        } else if (stageButtonId == R.id.checkin_btStage1)
        {
            xStageFare = db.getStageFare(WorkingSession.getInstance().journalRoute.ISN, 1);
            stageCount = 1;
        } else if (stageButtonId == R.id.checkin_btStage2)
        {
            xStageFare = db.getStageFare(WorkingSession.getInstance().journalRoute.ISN, 2);
            stageCount = 2;
        } else if (stageButtonId == R.id.checkin_btStage3)
        {
            xStageFare = db.getStageFare(WorkingSession.getInstance().journalRoute.ISN, 3);
            stageCount = 3;
        } else if (stageButtonId == R.id.checkin_btStage4)
        {
            xStageFare = db.getStageFare(WorkingSession.getInstance().journalRoute.ISN, 4);
            stageCount = 4;
        } else if (stageButtonId == R.id.checkin_btStage5)
        {
            xStageFare = db.getStageFare(WorkingSession.getInstance().journalRoute.ISN, 5);
            stageCount = 5;
        } else if (stageButtonId == R.id.checkin_btStage6)
        {
            xStageFare = db.getStageFare(WorkingSession.getInstance().journalRoute.ISN, 6);
            stageCount = 6;
        } else if (stageButtonId == R.id.checkin_btStage7)
        {
            xStageFare = db.getStageFare(WorkingSession.getInstance().journalRoute.ISN, 7);
            stageCount = 7;
        }

        if (xStageFare < 0)
        {
            WorkingSession.getInstance().ShowToast(CheckInV2CashMultiple.this,
                    "Could not get fare of Stage",
                    Toast.LENGTH_SHORT);
            xStageFare = 0;
        }
    }

    private TransactionValue CreateTransaction(String type, double topUpAmount, VoucherValue vv, boolean updateBalance)
    {
        TransactionValue trans = null;
        try
        {
            //---
            int adultCount = getSelectedPassenger(adult);
            int seniorCount = getSelectedPassenger(senior);
            int childCount = getSelectedPassenger(child);
            int disabledCount = getSelectedPassenger(disabled);
            //int exemptCount = getSelectedPassenger(exempt);
            int studentCount = getSelectedPassenger(student);

            String description = String.format("Check-in near %s",
                    currentLocation.StationName);
            /*if(checkinType != Declarations.CHECK_IN_TYPE_TAP_IN)
                description += String.format(" for %d stages. ", stageCount);
            else
                description += "[@checkout]. ";*/
			description += String.format(" for %d stages. ", stageCount);

            if (adultCount > 0)
                description += String.format("Adult: %d,", adultCount);
            if (seniorCount > 0)
                description += String.format(" Senior: %d,", seniorCount);
            if (childCount > 0)
                description += String.format(" Child: %d,", childCount);
            if (disabledCount > 0)
                description += String.format(" Disabled: %d,", disabledCount);
            /*if (exemptCount > 0)
                description += String.format(" Exempt: %d,", exemptCount);*/
            if (studentCount > 0)
                description += String.format(" Student: %d,", studentCount);

            description = description.substring(0, description.length() - 1);

            trans = WorkingSession.getInstance().CreateTransaction(
                    CheckInV2CashMultiple.this,
                    "CHECK-IN",
                    type,
					totalAmount,
                    0, //freight
                    0,//ExcessiveBag
                    topUpAmount,
                    vv,
                    currentLocation,
                    null,
                    xStageFare,
                    adultCount,
                    seniorCount,
                    childCount,
                    disabledCount,
                    0, //exemptCount,
                    studentCount,
                    null,
                    description
            );
            //--
            if (trans == null)
            {
                Message error = uiThreadHandler.CreateShowAlertDialogMsg(
                        "Create Transaction Error",
                        "System Error.\nCould not create transaction, please contact your administrator. [1]"
                );
                uiThreadHandler.sendMessage(error);

                /*WorkingSession.getInstance().ShowErrorDialog(
                        CheckIn.this,
                        "Create Transaction Error",
                        "System Error.\nCould not create transaction, please contact your administrator."
                );*/
                return null;
            }

            /*if (checkinType == Declarations.CHECK_IN_TYPE_NO_CARD ||
                    checkinType == Declarations.CHECK_IN_TYPE_NORMAL)
            {
                trans.CheckOutDate = new Date();
            }*/
			trans.CheckOutDate = new Date();

            try
            {
                long rx = db.addTransaction(trans);
                trans.ISN = (int) rx;
            }
            catch (Exception ex)
            {
                Message error = uiThreadHandler.CreateShowAlertDialogMsg(
                        "Create Transaction Error",
                        "System Error.\nCould not create transaction, please contact your administrator. [2]"
                );
                uiThreadHandler.sendMessage(error);

                /*WorkingSession.getInstance().ShowErrorDialog(
                        CheckIn.this,
                        "Create Transaction Error",
                        "System Error.\nCould not create transaction, please contact your administrator."
                );*/
                return null;
            }

            if (trans.ISN == 0)
            {
                Message error = uiThreadHandler.CreateShowAlertDialogMsg(
                        "Create Transaction Error",
                        "System Error.\nCould not create transaction, please contact your administrator. [3]"
                );
                uiThreadHandler.sendMessage(error);

                /*WorkingSession.getInstance().ShowErrorDialog(
                        CheckIn.this,
                        "Create Transaction Error",
                        "System Error.\nCould not create transaction, please contact your administrator."
                );*/
                return null;
            }
            //WorkingSession.getInstance().ShowToast(CheckIn.this, "Add transaction successful", Toast.LENGTH_SHORT);
            Message msg = uiThreadHandler.CreateShowToastMsg("Add transaction successful");
            uiThreadHandler.sendMessage(msg);
            //--
            if (updateBalance)
            {
                WorkingSession.getInstance().currentPassenger.CurrentBalance += trans.TopUpAmount - trans.FareAmount;
                int x = db.updateMemberBalance(
                        WorkingSession.getInstance().currentPassenger.ISN,
                        WorkingSession.getInstance().currentPassenger.CurrentBalance);
                if (x > 0)
                {
                    msg = uiThreadHandler.CreateShowToastMsg("Update customer balance successful");
                    uiThreadHandler.sendMessage(msg);
                    /*WorkingSession.getInstance().ShowToast(CheckIn.this,
                            "Update customer balance successful", Toast.LENGTH_SHORT);*/
                }
                else
                {
                    msg = uiThreadHandler.CreateShowToastMsg("Update customer balance failed");
                    uiThreadHandler.sendMessage(msg);
                    /*WorkingSession.getInstance().ShowToast(CheckIn.this,
                            "Update customer balance failed", Toast.LENGTH_SHORT);*/
                }
            }
        }
        catch (Exception ex)
        {
            ex.printStackTrace();
        }

        return trans;
    }

    private String CreateReceiptContent(TransactionValue xx)
    {
        Date date = new Date();
        String receiptDate = Utilities.DateToString(date, "dd/MM/yyyy");
        String receiptTime = Utilities.DateToString(date, "hh:mm a");

        String content = Utilities.StringAlignCenter(48, "BulaMy(Fiji) - BMF etikite  ") //+ "\n"
                + Utilities.StringAlignCenter(48, "BMF Make It Your Choice")
                + Utilities.StringAlignCenter(48, "www.bulamyfiji.com")
                + "\n\n"
                + Utilities.StringAlignLeftRight(48,
                    "Entry: " + currentLocation.StationName,
                    "Bus Reg.: " + WorkingSession.getInstance().journalBus.BusNumber
                ) + "\n"
                + Utilities.StringAlignLeftRight(48,
                    "Stages: " + stageCount,
                    "Driver: " + WorkingSession.getInstance().journalDriver.FullName
                ) + "\n"
                + Utilities.StringAlignLeftRight(48,
                    "No. PAX: " + String.valueOf(passengerCount),
                    "Company: DeeCees Fiji Ltd"
                ) + "\n"
                + Utilities.StringAlignLeftRight(48,
                    "Fare: " +  WorkingSession.getInstance().decimalFormat.format(xStageFare),
                    "TIN: 12683467161"
                ) + "\n"
                + Utilities.StringAlignLeftRight(48,
                    "Total: " +  String.valueOf(WorkingSession.getInstance().RoundMoney(totalAmount)),
                    "Issued: " + receiptDate
                ) + "\n"
                + Utilities.StringAlignLeftRight(48,
                    "ACCT Name: " ,
                    receiptTime
                ) + "\n"
                + Utilities.StringAlignLeftRight(48,
                    "ACCT #: " ,
                    "Mode: " + xx.Type
                ) + "\n"
                + Utilities.StringAlignLeftRight(48,
                    "Balance: ",
                    "Transaction ID: " +  xx.TransactionID
                ) + "\n"
                + "\nPlease Keep Receipt For Your Records\n\n";

        return content;
    }

    private boolean PrintReceipt(TransactionValue xx)
    {
		/*String x = db.getRuntimeValues("print-receipt");
		if(x == null || x.length() == 0)
			x = "1";
		if(x.equals("0"))
			return false;*/
		if(!WorkingSession.getInstance().printReceipt)
			return false;
		//--
        String receipt = CreateReceiptContent(xx);

        int rs = WorkingSession.getInstance().PreparePrintReceiptWifi(CheckInV2CashMultiple.this, receipt, printReceiptCallback);

        if (rs == Declarations.NO_WIFI_PRINTER_SETUP)
        {
            /*runOnUiThread(new Runnable()
            {
                @Override
                public void run()
                {
                    WorkingSession.getInstance().ShowToast(CheckIn.this, "No printer selected. Please setup one.", Toast.LENGTH_LONG);
                }
            });*/

            Message error = uiThreadHandler.CreateShowToastMsg(
                    "No printer selected. Please setup one.");
            uiThreadHandler.sendMessage(error);

            /*Message error = uiThreadHandler.CreateShowAlertDialogMsg(
                    "Print Receipt Error",
                    "No printer selected. Please setup one.");
            uiThreadHandler.sendMessage(error);*/

            //WorkingSession.getInstance().ShowToast(CheckIn.this, "No printer selected. Please setup one.", Toast.LENGTH_LONG);
        }
        else if (rs == Declarations.PRINT_RECEIPT_ERROR)
        {
            /*runOnUiThread(new Runnable()
            {
                @Override
                public void run()
                {
                    WorkingSession.getInstance().ShowToast(CheckIn.this, "Print receipt failed.", Toast.LENGTH_LONG);
                }
            });*/

            Message error = uiThreadHandler.CreateShowToastMsg(
                    "Print receipt failed.");
            uiThreadHandler.sendMessage(error);

            //WorkingSession.getInstance().ShowToast(CheckIn.this, "Print receipt failed.", Toast.LENGTH_LONG);
        }
        return rs == Declarations.PRINT_RECEIPT_WAITING;
    }

    private final Handler printReceiptCallback = new Handler()
    {
        @Override
        public void handleMessage(Message msg)
        {
			processing = false;
            Message error = null;
            switch (msg.what)
            {
				case Declarations.WIFI_PRINTER_CONNECTED:
					WorkingSession.getInstance().ShowToast(CheckInV2CashMultiple.this,
							"Printer connected", Toast.LENGTH_SHORT);
					WorkingSession.getInstance().PrintReceipt();
					break;
                case Declarations.WIFI_PRINTER_CONNECTED_ERR:
                    Log.d(TAG, String.format(
                            "WIFI_PRINTER_CONNECTED_ERR. Unable connect to printer %s",
                            WorkingSession.getInstance().wifiPrinterAddress)
                    );
                    /*WorkingSession.getInstance().ShowToast(CheckIn.this,
                            "Unable connect to printer", Toast.LENGTH_SHORT);*/
                    progress.dismiss();
                    //--
                    AlertDialog.Builder dialog = new AlertDialog.Builder(CheckInV2CashMultiple.this);
                    dialog.setNegativeButton("OK", new DialogInterface.OnClickListener()
                    {
                        @Override
                        public void onClick(DialogInterface dialog, int which)
                        {
                            uiThreadHandler.sendEmptyMessage(UIThreadHandler.DO_BACK_PRESS);
                        }
                    });
                    AlertDialog alert = dialog.create();
                    alert.setTitle("Print Receipt Error");
                    alert.setMessage(
                            String.format("Unable connect to printer %s",
                                    WorkingSession.getInstance().wifiPrinterAddress)
                    );
                    //--
                    alert.show();
                    //--
                    break;
                case Declarations.WIFI_PRINTER_SEND_FAILED:
                    error = uiThreadHandler.CreateShowToastMsg(
                            "Unable send data to printer.");
                    uiThreadHandler.sendMessage(error);

                    /*WorkingSession.getInstance().ShowToast(CheckIn.this,
                            "Unable send data to printer", Toast.LENGTH_SHORT);*/
                    break;
                case Declarations.PRINT_RECEIPT_SUCCESSFUL:
                    error = uiThreadHandler.CreateShowToastMsg(
                            "Print receipt successful.");
                    uiThreadHandler.sendMessage(error);
                    /*WorkingSession.getInstance().ShowToast(CheckIn.this,
                            "Print receipt successful", Toast.LENGTH_SHORT);*/
                    //onBackPressed();
                    uiThreadHandler.sendEmptyMessage(UIThreadHandler.DO_BACK_PRESS);
                    break;
            }
        }
    };

    private void doPayByCash()
    {
        try
        {
            TransactionValue trans = CreateTransaction("Cash", 0, null, false);

			//-------------------TEST-------------------
			WorkingSession.getInstance().transactionCount++;
			//-------------------TEST-------------------
			if (!PrintReceipt(trans))
			{
				uiThreadHandler.sendEmptyMessage(UIThreadHandler.DO_BACK_PRESS);
				//onBackPressed();
			}
        }
        catch (Exception ex)
        {
            Log.e(TAG, "doPayByCash: " + ex.getMessage());
            Message error = uiThreadHandler.CreateShowAlertDialogMsg(
                    "System Error",
                    ex.getMessage()
            );
            uiThreadHandler.sendMessage(error);
            /*WorkingSession.getInstance().ShowErrorDialog(
                    CheckIn.this,
                    "System Error",
                    ex.getMessage());*/
        }
    }

    //this function is called in onActivityResult
    private void doPayByStudentVoucher(
            String voucherType, double discountAmount,
            int collectBalanceType, double collectAmount)
    {
        try
        {
            VoucherValue vv = new VoucherValue();
            vv.VoucherType = voucherType;
            vv.VoucherAmount = discountAmount;

            TransactionValue trans = null;
            if (collectBalanceType == StudentVoucher.COMPLETE_PAYMENT_BY_VOUCHER)
            {
                trans = CreateTransaction(
                        "Student-Voucher",
                        0,
                        vv,
                        false);
            } else if (collectBalanceType == StudentVoucher.COMPLETE_PAYMENT_BY_BMF)
            {
                trans = CreateTransaction(
                        "BMF",
                        0,
                        vv,
                        false);
            } else if (collectBalanceType == StudentVoucher.COMPLETE_PAYMENT_BY_CASH)
            {
                trans = CreateTransaction(
                        "Cash",
                        collectAmount,
                        vv,
                        false);
            }
            if (trans == null)
            {
                WorkingSession.getInstance().ShowErrorDialog(
                        CheckInV2CashMultiple.this,
                        "Error",
                        "System Error.\nCould not add Transaction"
                );
				processing = false;
                return;
            }
			//-------------------TEST-------------------
			WorkingSession.getInstance().transactionCount++;
			//-------------------TEST-------------------
			if (!PrintReceipt(trans))
			{
				uiThreadHandler.sendEmptyMessage(UIThreadHandler.DO_BACK_PRESS);
				//onBackPressed();
			}
        }
        catch (Exception ex)
        {
            Log.e(TAG, "doPayByStudentVoucher: " + ex.getMessage());
            Message error = uiThreadHandler.CreateShowAlertDialogMsg(
                    "System Error",
                    ex.getMessage()
            );
            uiThreadHandler.sendMessage(error);

            /*WorkingSession.getInstance().ShowToast(CheckIn.this, ex.getMessage(),
                    Toast.LENGTH_LONG);*/
        }
    }

    OnClickListener onCancelClick = new OnClickListener()
    {
        @Override
        public void onClick(View v)
        {

            onBackPressed();
        }
    };

    @Override
    public void onBackPressed()
    {
		try
		{
			progress.dismiss();
		}
		catch (Exception ex)
		{
			Log.e(TAG, "[onBackPress] " + ex.toString());
		}
		//--
		Intent next = new Intent(CheckInV2CashMultiple.this, Main.class);

		next.putExtra("INPUT_DIRECT_CHECK_IN", 0);
		if(Main.getInstance() != null)
			Main.getInstance().setIntent(next);

		//super.onBackPressed();
		//--
		finish();
    }

//    @Override
//    public void onNewIntent(Intent intent)
//    {
//        String action = intent.getAction();
//        Log.d(TAG, String.format("[onNewIntent] Action: %s", action));
//
//        if (action != null && action.equals(NfcAdapter.ACTION_TAG_DISCOVERED)
//            || action.equals(NfcAdapter.ACTION_NDEF_DISCOVERED)
//			&& !processing)
//        {
//            String[] result = Utilities.readNFCTagContentAndSerial(CheckInV2CashMultiple.this, intent);
//            //--result[0] = TagSerial, result[1] = Tag content
//            if (result == null || result.length < 2)
//                return;
//
//            if (result[1].length() == 0)
//            {
//				WorkingSession.getInstance().ShowErrorDialog(
//                        CheckInV2CashMultiple.this,
//						"Error",
//                        "Invalid NFC Tag content"
//                );
//				return;
//            }
//
//            MemberValue member = db.getMemberByCard(result[1], result[0]);
//
//            if (member != null)
//            {
//				// go back to Home
//				Intent mainScreen = new Intent(CheckInV2CashMultiple.this, Main.class);
//				mainScreen.putExtra("INPUT_CUSTOMER", member.CardNumber);
//				//startActivity(mainScreen);
//
//				if(Main.getInstance() != null)
//					Main.getInstance().setIntent(mainScreen);
//				finish();
//            }
//            else
//            {
//                //Utilities.PlayMedia(CheckIn.this, "C.mp3");
//                WorkingSession.getInstance().ShowErrorDialog(
//                        CheckInV2CashMultiple.this,
//                        "Error",
//                        "Invalid Card Number: " + result[1]
//                );
//            }
//        }
//        else
//        {
//            Log.d(TAG, "Action: " + action + ", on processing current task");
//        }
//    }

    @Override
    protected void onResume()
    {
        Log.d(TAG, "[onResume] ....");
        super.onResume();
//        if (nfcAdapter != null)
//        {
//            nfcAdapter.enableForegroundDispatch(this, mPendingIntent, null, null);
//            // mAdapter.enableForegroundNdefPush(this);
//        }
    }

    @Override
    protected void onPause()
    {
        Log.d(TAG, "[onPause] ....");
        super.onPause();
//        if (nfcAdapter != null)
//        {
//            nfcAdapter.disableForegroundDispatch(this);
//            //nfcAdapter.disableForegroundNdefPush(this);
//            nfcAdapter.setNdefPushMessage(null, this);
//        }
        if(errorVoice != null)
            errorVoice.stop();
        //WorkingSession.getInstance().CancelShowingToast();
    }

    @Override
    protected void onDestroy()
    {
        Log.d(TAG, "[onDestroy] ....");
        super.onDestroy();
        /*if (autoSubmit != null)
            autoSubmit.cancel();*/
        if(errorVoice != null)
            errorVoice.stop();

    }

    private int lastCheckId = 0;
    private RadioGroup.OnCheckedChangeListener onPassengerCheckedChange = new RadioGroup.OnCheckedChangeListener()
    {
        @Override
        public void onCheckedChanged(RadioGroup radioGroup, int i)
        {
            Log.d(TAG, "[onPassengerCheckedChange] id: " + i);

            if (i == -1)
                return;
            //--
            if (i == lastCheckId)
                return;
            //--
            lastCheckId = i;
            //--
            if (!((RadioButton) findViewById(i)).isChecked())
                return;

            CalcTotalAmount();
            //--
            String selectText = ((RadioButton) findViewById(radioGroup.getCheckedRadioButtonId())).getText().toString();

            if (selectText.equals("0"))
                return;
            /*if (checkinType == Declarations.CHECK_IN_TYPE_TAP_IN)
                return;*/
            //--
			int xCount = db.getStageCountOfRoute(WorkingSession.getInstance().journalRoute.ISN);
            if (radioGroup.getId() != R.id.Student)
            {
                student.check(R.id.Student0);
				//--
				Button btn = (Button)findViewById(R.id.check_in_multiple_cash);
				btn.setEnabled(true);
				//--
				btn = (Button)findViewById(R.id.check_in_multiple_student_voucher);
				btn.setVisibility(View.GONE);
				//--
				btn = (Button)findViewById(R.id.check_in_multiple_cash);
				btn.setVisibility(View.VISIBLE);
				//--
				for(int xx=1;xx<=xCount && xx<8;xx++)
				{
					int id = Utilities.getResId("checkin_btStage" + xx,
							CheckInV2CashMultiple.this,
							R.id.class
					);
					if(id > -1)
					{
						findViewById(id).setEnabled(true);
					}
				}
            }
			else //check student
            {
                adult.check(R.id.Adult0);
                senior.check(R.id.Senior0);
                child.check(R.id.Child0);
                disabled.check(R.id.Disabled0);
				//--
				Button btn = (Button)findViewById(R.id.check_in_multiple_cash);
				btn.setEnabled(false);
				//--
				btn = (Button)findViewById(R.id.check_in_multiple_student_voucher);
				btn.setVisibility(View.VISIBLE);
				//--
				btn = (Button)findViewById(R.id.check_in_multiple_cash);
				btn.setVisibility(View.GONE);
				//--
				int xx = -1;
				if(xCount > 3)
					xx = 4;

				while(xx >0 && xx<=xCount && xx<8)
				{
					int id = Utilities.getResId("checkin_btStage" + xx,
							CheckInV2CashMultiple.this,
							R.id.class
					);
					if(id > -1)
					{
						findViewById(id).setEnabled(false);
					}
					xx++;
				}
            }
        }
    };

    private final class UIThreadHandler extends Handler
    {
        private final String TAG = "CheckInUIThreadHandler";
        public static final int MSG_COUNT_DOWN = 0x10;
        public static final int SHOW_TOAST = 0x11;
        public static final int SHOW_ALERT_DIALOG = 0x12;
        public static final int DO_CHECK_IN_BY_CASH = 0x13;
        public static final int DO_BACK_PRESS = 0x14;
        private int currentCountDownValue = Declarations.TAP_IN_TIMEOUT_SECONDS;


        public UIThreadHandler(Looper lp)
        {
            super(lp);
        }

        @Override
        public void handleMessage(Message msg)
        {
            try
            {
                switch (msg.what)
                {
                    /*case UIThreadHandler.MSG_COUNT_DOWN:
                    {
                        Log.d(TAG, "Countdown: " + currentCountDownValue);
                        WorkingSession.getInstance().ShowToast(
                                CheckInV2CashMultiple.this,
                                String.valueOf(currentCountDownValue),
                                Toast.LENGTH_SHORT);
                        currentCountDownValue--;
                        if (currentCountDownValue < 0)
                        {
                            autoSubmit.cancel();
                            onSubmitClick.onClick(null);
                        }

                        break;
                    }*/
                    case UIThreadHandler.SHOW_TOAST:
                    {
                        String content = msg.getData().getString("TOAST_CONTENT", "");
                        if(content.length() == 0)
                            break;
                        WorkingSession.getInstance().ShowToast(
                                CheckInV2CashMultiple.this,
                                content,
                                Toast.LENGTH_SHORT);
                        break;
                    }
                    case UIThreadHandler.SHOW_ALERT_DIALOG:
                    {
                        String title = msg.getData().getString("DIALOG_TITLE", "");
                        String content = msg.getData().getString("DIALOG_CONTENT", "");
                        if(content.length() == 0)
                            break;
                        WorkingSession.getInstance().ShowErrorDialog(
                                CheckInV2CashMultiple.this,
                                title,
                                content);
                        break;
                    }
                    case DO_CHECK_IN_BY_CASH:
                    {
                        Thread.sleep(500);
                        Log.d(TAG, "Do Check-in by cash");
                        //--
                        DoCheckInAsync xTask = new DoCheckInAsync(
                                CheckInV2CashMultiple.this,
                                progress,
                                DoCheckInAsync.CHECK_IN_BY_CASH
                        );
                        xTask.execute();
                        //--
                        break;
                    }
                    case DO_BACK_PRESS:
                        Thread.sleep(500);
						runOnUiThread(new Runnable()
						{
							@Override
							public void run()
							{
								onBackPressed();
							}
						});
                }
            }
            catch (Exception ex)
            {
                Log.e(TAG, String.format("[MSG:%d] %s", msg.what, ex.getMessage()));
            }
        }

        public Message CreateShowToastMsg(String content)
        {
            Message msg = new Message();
            msg.what = SHOW_TOAST;

            Bundle data = new Bundle();
            data.putString("TOAST_CONTENT", content);
            msg.setData(data);

            return msg;
        }

        public Message CreateShowAlertDialogMsg(String dialogTitle, String content)
        {
            Message msg = new Message();
            msg.what = SHOW_ALERT_DIALOG;

            Bundle data = new Bundle();
            data.putString("DIALOG_TITLE", dialogTitle);
            data.putString("DIALOG_CONTENT", content);
            msg.setData(data);

            return msg;
        }
    }
    
    /*private boolean isStageButton(int checkId)
    {
        return checkId == R.id.checkin_btStage1
        || checkId == R.id.checkin_btStage2
        || checkId == R.id.checkin_btStage3
        || checkId == R.id.checkin_btStage4
        || checkId == R.id.checkin_btStage5
        || checkId == R.id.checkin_btStage6
        || checkId == R.id.checkin_btStage7;
    }*/

    public class DoCheckInAsync extends AsyncTask<Object, Void, Void>
    {
        //public static final int CHECK_IN_BY_BMF = 1000;
        public static final int CHECK_IN_BY_CASH = 1001;
        //public static final int CHECK_IN_BY_CASH_TOP_UP = 1002;
        public static final int CHECK_IN_BY_STUDENT_VOUCHER = 1003;
       // public static final int CHECK_IN_BY_TAP_IN = 1004;

        private ProgressDialog progress;
        private Context callerContext;
        private int checkInType;

        public DoCheckInAsync(Context context, ProgressDialog dialog, int checkInType)
        {
            callerContext = context;
            progress = dialog;
            this.checkInType = checkInType;
        }

        public void onPreExecute()
        {
            processing = true;
            progress.show();
            //--
            super.onPreExecute();
        }

        public Void doInBackground(Object... inputValues)
        {
            try
            {
                switch (this.checkInType)
                {
                    case CHECK_IN_BY_CASH:
                        doPayByCash();
                        break;
                    /*case CHECK_IN_BY_BMF:
                        doPayByBMF();
                        break;
                    *//*case CHECK_IN_BY_TAP_IN:
                        doTapIn();
                        break;*//*
                    case CHECK_IN_BY_CASH_TOP_UP:
                        doPayCashAndTopUp(((Number)inputValues[0]).doubleValue());
                        break;*/
                    case CHECK_IN_BY_STUDENT_VOUCHER:
                        doPayByStudentVoucher(
                                String.valueOf(inputValues[0]), //voucherType
                                ((Number)inputValues[1]).doubleValue(), //discountAmount
                                ((Number)inputValues[2]).intValue(), //collectBalanceType
                                ((Number)inputValues[3]).doubleValue() //collectAmount
                        );
						break;
                }
            }
            catch (Exception ex)
            {
                Log.e(TAG, "[DoCheckInAsync] " + ex.getMessage());
            }

            return null;
        }

        public void onPostExecute(Void unused)
        {
            processing = false;
            super.onPostExecute(unused);
        }
    }

	private void RegisterPayByButtonEvent()
	{
		Button btn = (Button)findViewById(R.id.check_in_multiple_cash);
		btn.setOnClickListener(onPaybyCash);
		//--
		btn = (Button)findViewById(R.id.check_in_multiple_refund);
		btn.setOnClickListener(onRefundClick);
		//--
		btn = (Button)findViewById(R.id.check_in_multiple_cancel);
		btn.setOnClickListener(onCancelClick);
		//--
		btn = (Button)findViewById(R.id.check_in_multiple_student_voucher);
		btn.setOnClickListener(onStudentVoucherClick);
	}

	private OnClickListener onRefundClick = new OnClickListener()
	{
		@Override
		public void onClick(View v)
		{
			Intent input = new Intent(CheckInV2CashMultiple.this, refund.class);
			input.putExtra("OPTION_NO_CARD", 1);
			startActivity(input);
		}
	};

	private void ChangeTitle()
	{
		TextView title = (TextView) findViewById(R.id.title_text);
		title.setText(getString(R.string.title_activity_check_in_no_card));
	}
}
